# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : logger.py
# Time       ：2023/1/27 20:19
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    日志文件配置
    logger config
"""
import datetime
import os
import sys
import logging
import platform
from collections import defaultdict
from time import strftime

from conf.config import LoggerConfig

PATH = os.path.join(LoggerConfig.logger_path, 'orderlines_logs')
FMT = LoggerConfig.FMT
DATE_FMT = LoggerConfig.DATE_FMT


class Logger(object):
    def __init__(self):
        self.logger = logging.getLogger()
        self.formatter = logging.Formatter(fmt=FMT, datefmt=DATE_FMT)
        self.log_filename = os.path.join(PATH, f'{strftime("%Y-%m-%d")}.log')
        if not os.path.exists(os.path.abspath(PATH)):
            os.makedirs(PATH)
        self.logger.addHandler(self.get_file_handler(self.log_filename))
        self.logger.addHandler(self.get_console_handler())
        # 设置日志的默认级别,Set the default log level
        self.logger.setLevel(logging.INFO)
        self.logger_stock = defaultdict(list)

    # 输出到文件handler的函数定义
    def get_file_handler(self, filename):
        file_handler = logging.FileHandler(filename, encoding="utf-8")
        file_handler.setFormatter(self.formatter)
        return file_handler

    # 输出到控制台handler的函数定义,Output a function definition to the console handler
    def get_console_handler(self):
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(self.formatter)
        return console_handler

    @property
    def current_time(self):
        return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    def info(self, msg, task_instance_id: str = None, ):
        self.logger.info(msg)
        if task_instance_id:
            self.logger_stock[task_instance_id].append(f'{self.current_time} INFO {msg}\n')

    def debug(self, msg):
        if LoggerConfig.debug:
            self.logger.debug(msg)

    def error(self, msg, task_instance_id: str = None):
        self.logger.error(msg)
        if task_instance_id:
            self.logger_stock[task_instance_id].append(f'{self.current_time} ERROR {msg}\n')

    def warn(self, msg, task_instance_id: str = None):
        self.logger.warning(msg)
        if task_instance_id:
            self.logger_stock[task_instance_id].append(f'{self.current_time} WARN {msg}\n')

    def clear_log_stock(self, task_instance_id: str):
        if self.logger_stock.get(task_instance_id):
            self.logger_stock.pop(task_instance_id)

    def log_text(self, task_instance_id: str):
        if self.logger_stock.get(task_instance_id):
            logs = '\n'.join(self.logger_stock[task_instance_id])
        else:
            logs = ''
        self.clear_log_stock(task_instance_id)

        return logs


logger = Logger()
